package net.csdn.business.notify.api.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import net.csdn.business.notify.common.config.AsyncThreadPoolConfig;
import net.csdn.business.notify.common.enums.ResultCodeEnum;
import net.csdn.business.notify.common.exception.BusinessException;
import net.csdn.business.notify.common.mapper.NotifyRemindRecordMapper;
import net.csdn.business.notify.common.model.dto.UpdateNotifyRemindRecordDTO;
import net.csdn.business.notify.common.model.entity.NotifyRemindRecord;
import net.csdn.business.notify.common.model.query.NotifyRemindRecordQuery;
import net.csdn.business.notify.common.model.vo.NotifyRemindRecordVO;
import net.csdn.business.notify.api.service.INotifyRemindRecordService;
import net.csdn.business.notify.common.model.vo.UserInfoVO;
import net.csdn.business.notify.common.model.vo.UserRemindRecordVO;
import net.csdn.business.notify.feign.SystemFeignClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;


/**
 * 通知中心-用户通知记录Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-11-27
 */
@Slf4j
@Service
public class NotifyRemindRecordServiceImpl extends ServiceImpl<NotifyRemindRecordMapper, NotifyRemindRecord> implements INotifyRemindRecordService
{

    @Resource(name= AsyncThreadPoolConfig.ASYNC_EXECUTOR_POOL_NAME)
    private ThreadPoolTaskExecutor asyncExecutor;

    @Autowired
    private SystemFeignClient userFeignClient;

    /**
     * 分页查询通知中心-用户通知记录列表
     *
     * @param query 通知中心-用户通知记录
     * @return 通知中心-用户通知记录
     */
    @Override
    public Page<NotifyRemindRecordVO> findPageList(NotifyRemindRecordQuery query) {
        //获得Page对象
        Page<NotifyRemindRecordVO> page = query.getPage();
        List<NotifyRemindRecordVO> pageList=baseMapper.findPageList(page,query);
        page.setRecords(pageList);
        return page;
    }

    /**
     * 根据id查询通知中心-用户通知记录
     * 
     * @param id 通知中心-用户通知记录主键
     * @return 通知中心-用户通知记录
     */
    @Override
    public NotifyRemindRecordVO selectNotifyRemindRecordById(String id)
    {
        NotifyRemindRecordVO notifyRemindRecordVO=baseMapper.selectNotifyRemindRecordById(id);
        if(notifyRemindRecordVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        return notifyRemindRecordVO;
    }

    /**
     * 查询通知中心-用户通知记录列表
     * 
     * @param query 通知中心-用户通知记录
     * @return 通知中心-用户通知记录
     */
    @Override
    public List<NotifyRemindRecordVO> selectNotifyRemindRecordList(NotifyRemindRecordQuery query)
    {
        return baseMapper.selectNotifyRemindRecordList(query);
    }

    /**
     * 删除通知中心-用户通知记录信息
     * 
     * @param id 通知中心-用户通知记录主键
     * @return 结果
     */
    @Override
    public Integer deleteNotifyRemindRecordById(String id)
    {
        //根据id查询是否存在
        NotifyRemindRecordVO notifyRemindRecordVO=baseMapper.selectNotifyRemindRecordById(id);
        if(notifyRemindRecordVO==null){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"id");
        }
        return baseMapper.deleteNotifyRemindRecordById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public Integer insertBatch(List<NotifyRemindRecord> list) {
        return baseMapper.insertBatch(list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    public Integer updateSendStatusBatch(UpdateNotifyRemindRecordDTO params) {
        return baseMapper.updateSendStatusBatch(params);
    }

    @Override
    public Page<UserRemindRecordVO> userRemindPage(NotifyRemindRecordQuery query) {
        String currUserId=query.getCurrUserId();
        if(StringUtils.isBlank(currUserId)){
            throw new BusinessException(ResultCodeEnum.PARAMETER_ERROR_CUSTOM,"currUserId");
        }
        //获得Page对象
        Page<UserRemindRecordVO> page = query.getPage();
        List<UserRemindRecordVO> pageList=baseMapper.userRemindPage(page,query);
        //循环组装用户信息
        if(pageList!=null&&pageList.size()>0){
            //List<String> userIds=new ArrayList<>();
            List<String> unReadIdList=new ArrayList<>();
            pageList.stream().forEach(remindVO->{
                String senderId=remindVO.getSenderId();
                //userIds.add(senderId);
                //判断已读未读状态，如果未读，放入集合
                Integer readState=remindVO.getReadState();
                if(readState==0){
                    unReadIdList.add(remindVO.getObjectId());
                }
            });
            //userIds.add(currUserId);
            try {
                /*Future<Map<String, UserInfoVO>> taskA =asyncExecutor.submit(()->{
                    //批量查询用户信息
                    Map<String, UserInfoVO> userInfoMap=new HashMap<>();
                    try {
                        userInfoMap=userFeignClient.batchQuery(userIds);
                    }catch (Exception e){
                        log.info("query remote user info error");
                    }
                    return userInfoMap;
                });*/
                if(unReadIdList.size()>0){
                    //异步批量更新状态为已读
                    asyncExecutor.execute(()->{
                        baseMapper.updateReadState(unReadIdList);
                    });
                }
                //Map<String, UserInfoVO> finalUserInfoMap = taskA.get();
                /*pageList.stream().parallel().forEach(remindVO->{
                    String senderId=remindVO.getSenderId();
                    String receiverId=remindVO.getReceiverId();
                    UserInfoVO senderInfo = finalUserInfoMap.get(senderId);
                    if(senderInfo!=null){
                        remindVO.setSenderName(senderInfo.getUsername());
                        remindVO.setSenderPhoto(senderInfo.getPhoto());
                    }
                    UserInfoVO receiverInfo = finalUserInfoMap.get(receiverId);
                    if(receiverInfo!=null){
                        remindVO.setReceiverName(receiverInfo.getUsername());
                        remindVO.setReceiverPhoto(receiverInfo.getPhoto());
                    }
                });*/
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        page.setRecords(pageList);
        return page;
    }

    @Override
    public int getUnReadCount(String currUserId) {
        return baseMapper.getUnReadCount(currUserId);
    }

    @Override
    public int markRead(String currUserId) {
        return baseMapper.markRead(currUserId);
    }
}
